﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CDStore3Tiers;

namespace CuaHangDiaNhac
{
	public partial class frmConfig : DevComponents.DotNetBar.Office2007RibbonForm
	{
		log4net.ILog log = log4net.LogManager.GetLogger("Cấu hình");
		public frmConfig()
		{
			InitializeComponent();

		}
		private void frmConfig_Load(object sender, EventArgs e)
		{
			txtServername.Focus();
			log.Info("Người dùng đã load lên form cấu hình");
		}

		private void buttonX1_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void btnTest_Click(object sender, EventArgs e)
		{
			try
			{
				string serVer = txtServername.Text.Trim();
				string db = txtDatabase.Text.Trim();
				string connection = "Data Source=" + serVer + ";Initial Catalog=" + db + ";Integrated Security=True";
				StoreCDDataContext cn = new StoreCDDataContext(connection);

				if (cn.TaiKhoans.Count() > 0)
					MessageBox.Show("Connection successful !", "Information !", MessageBoxButtons.OK, MessageBoxIcon.Information);
				btnOK.Enabled = true;

			}
			catch
			{
				txtServername.Focus();
				btnOK.Enabled = false;
				MessageBox.Show("Connection failed !", "Information !", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			log.Info("Người dùng kiểm tra kết nối cơ sở dữ liệu");
		}

		private void btnOK_Click(object sender, EventArgs e)
		{

			//getConfig XL = new getConfig();
			getConfig.ghiFileConfig(txtServername.Text, txtDatabase.Text);
			string serVer = txtServername.Text.Trim();
			string db = txtDatabase.Text.Trim();
			string connection = "Data Source=" + serVer + ";Initial Catalog=" + db + ";Integrated Security=True";
			SetLog4NetAppenderConnectionString(GetConn4Log());
			this.Close();
			log.Info("Người dùng kết nối tới server: " + serVer + " và cơ sở dữ liệu: " + db);
		}

		public string GetConn4Log()
		{
			return getConfig.getConnection();
		}
		public void SetLog4NetAppenderConnectionString(string connectionString)
		{
			log4net.Repository.Hierarchy.Hierarchy hierarchy =
				log4net.LogManager.GetLoggerRepository()
					as log4net.Repository.Hierarchy.Hierarchy;

			if (hierarchy != null)
			{
				log4net.Appender.AdoNetAppender appender
					= (log4net.Appender.AdoNetAppender)hierarchy.GetAppenders()
						.Where(x => x.GetType() ==
							typeof(log4net.Appender.AdoNetAppender))
						.FirstOrDefault();

				if (appender != null)
				{
					appender.ConnectionString = connectionString;
					appender.ActivateOptions();
				}
			}
		}

	}
}
